package com.wongoing.aop;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.wongoing.annotation.Token;

/**
 * 功能说明：SpringMVC token拦截器，防止表单重复提交
 * 修改说明：
 * @author zhenglibing
 * @date 2017年10月31日 下午2:22:59
 * @version 0.1
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
	/**
	 * 开始处理请求
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod)handler;
			Method method = handlerMethod.getMethod();
			Token annotation = method.getAnnotation(Token.class);
			if (annotation != null) {
				boolean needSaveSession = annotation.save();
				if (needSaveSession) {
					request.getSession(false).setAttribute("token", UUID.randomUUID().toString());;
				}
				boolean needRemoveSession = annotation.remove();
				if (needRemoveSession) {
					if (this.isRepeatSubmit(request)) {
						return false;
					}
					request.getSession(false).removeAttribute("token");
				}
			}
			return true;
		}
		else {
			return super.preHandle(request, response, handler);
		}
	}
	
	/**
	 * 功能说明：判断请求是否为重复提交
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月31日 下午2:30:48
	 * @param request
	 * @return
	 */
	private boolean isRepeatSubmit(HttpServletRequest request) {
		String serverToken = (String)request.getSession(false).getAttribute("token");
		if (serverToken == null) {
			return true;
		}
		String clientToken = request.getParameter("token");
		if (clientToken == null) {
			return true;
		}
		if (!serverToken.equals(clientToken)) {
			return true;
		}
		return false;
	}
	
	/**
	 * 请求处理完毕，页面呈现之前
	 */
//	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) throws Exception {
//		
//	}
	
	/**
	 * 页面呈现后指定的回调
	 */
//	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
//			throws Exception {
//		
//	}
}
